package cn.sort;

//将一个单向链表 按某值划分左边小,中间相等,右边大的形式.
public class SmallerEqualBigger {

    public static class Node{
        private int value;
        private Node next;
        public Node(int data){
            this.value = data;
        }
    }

    //参数 单向链表的头,和比较大小的数
    public static Node listPartition1(Node head,int pivot){
        if (null == head) {
            return head;
        }
        Node cur = head;
        int i = 0;
        while (cur != null){
            i++;
            cur = cur.next;
        }
        Node[] nodeArr = new Node[i];
        i= 0;
        cur = head;
        for (i = 0; i < nodeArr.length; i++) {
            nodeArr[i] = cur;
            cur = cur.next;
        }
        arrPartition(nodeArr,pivot);
        for(i = 1; i!=nodeArr.length;i++){
            nodeArr[i-1].next = nodeArr[i];
        }
        nodeArr[i-1] = null;
        return nodeArr[0];
    }

    private static void arrPartition(Node[] nodeArr, int pivot) {
        int small = -1;
        int big = nodeArr.length;
        int index = 0;
        while (index != big){
            if(nodeArr[index].value < pivot){
                swap(nodeArr,++small,index++);
            } else if(nodeArr[index].value == pivot){
                index++;
            }else{
                swap(nodeArr,--big,index);
            }
        }
    }

    private static void swap(Node[] nodeArr, int i, int index) {
        Node tmp = nodeArr[i];
        nodeArr[i] = nodeArr[index];
        nodeArr[index] = tmp;
    }
    public static Node listParttion2(Node head,int pivot){
        Node sH = null;
        Node sT = null;
        Node eH = null;
        Node eT = null;
        Node bH = null;
        Node bT = null;
        Node next = null;
        while (head != null){
            next = head.next;
            head.next = null;
            if (head.value < pivot) {
                if(sH == null){
                    sH = head;
                    sT = head;
                } else {
                    sT.next = head;
                    sT = head;//尾部
                }
            } else if(head.value == pivot){
                if(sH == null){
                    eH = head;
                    eT = head;
                } else {
                    eT.next = head;
                    eT = head;//尾部
                }
            } else {
                if(bH == null){
                    bH = head;
                    bT = head;
                } else {
                    bT.next = head;
                    bT = head;//尾部
                }
            }
        }

        if(sT != null){
            sT.next = eH;
            eT = eT == null?sT:eT;
        }
        if(eT !=  null){
            eT.next = bH;
        }

        return sH != null?sH:eH != null?eH:bH;
    }

}
